﻿using System;
using System.ServiceModel;

namespace ListenToQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Press <ENTER> to start listening.");
                Console.ReadLine();

                // Create a ServiceHost for the EchoServiceImpl type
                // and use the base address from app.config
                ServiceHost host = new ServiceHost(typeof(AzureStorageAdapterNamespace.AzureStorageAdapterService));

                // Open the ServiceHost to start listening for messages
                host.Open();

                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.ReadLine();

                // Close the ServiceHost
                host.Close();
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine();
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine();
            }
        }

        public static GetMessageResponse OnGetMessage(GetMessageRequest request)
        {
            Console.WriteLine(String.Format("<QueueMessage>"));
            Console.WriteLine(String.Format("  <MessageId>{0}</MessageId>", request.QueueMessage.MessageId));
            if (!String.IsNullOrEmpty(request.QueueMessage.InsertionTime))
                Console.WriteLine(String.Format("  <InsertionTime>{0}</InsertionTime>", request.QueueMessage.InsertionTime));
            if (!String.IsNullOrEmpty(request.QueueMessage.ExpirationTime))
                Console.WriteLine(String.Format("  <ExpirationTime>{0}</ExpirationTime>", request.QueueMessage.ExpirationTime));
            if (!String.IsNullOrEmpty(request.QueueMessage.PopReceipt))
                Console.WriteLine(String.Format("  <PopReceipt>{0}</PopReceipt>", request.QueueMessage.PopReceipt));
            if (!String.IsNullOrEmpty(request.QueueMessage.NextVisibleTime))
                Console.WriteLine(String.Format("  <NextVisibleTime>{0}</NextVisibleTime>", request.QueueMessage.NextVisibleTime));
            Console.WriteLine(String.Format("  <MessageText>{0}</MessageText>", request.QueueMessage.MessageText));
            Console.WriteLine(String.Format("</QueueMessage>"));

            return new GetMessageResponse();
        }
    }
}
